package com.dhcc.sdc.base.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcOrdmastEntity;
import com.dhcc.cdc.busi.service.*;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sdc.base.entity.SdcBaseAssessmentEntity;
import com.dhcc.sdc.cdss.dto.SdcBaseAssessmentDto;
import com.dhcc.sdc.cdss.entity.*;
import com.dhcc.sdc.cdss.service.*;
import com.dhcc.sdc.base.entity.CdssRecommendKeywordEntity;
import com.dhcc.sdc.base.service.ICdssRecommendKeywordService;
import com.dhcc.sdc.base.service.ICdssStandardMatchService;
import com.dhcc.sds.standard.dto.CdcOrdmastDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 标准化_cdss推荐信息对照
 *
 * @ClassName: CdssStandardMatchController
 * @Description: TODO
 * @author zhangdc
 * @date 2022-06-30 10:09:56
 */
@Controller
@RequestMapping("${sys.backendPath}/cdss/cdssstandardmatch")
public class CdssStandardMatchController extends BaseController {

    private String PREFIX = "/backend/sdc/cdssstandardmatch/";

    @Autowired
    private ICdssStandardMatchService cdssStandardMatchService;
    @Autowired
    private ICdssRecommendKeywordService cdssRecommendKeywordService;
    @Autowired
    private ICdcOrdmastService ordmastService;
    @Autowired
    private ICdcLabOrderService labOrderService;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private ICdcDictionaryService cdcDictionaryService;
    @Autowired
    private ISdcCdssItemService sdcCdssItemService;
    @Autowired
    private ISdcCdssItemMatchService sdcCdssItemMatchService;
    @Autowired
    private ISdcCdssContraindicationMatchService sdcCdssContraindicationMatchService;


    /**
     * 跳转到标准化_cdss推荐信息对照列表首页
     */
    @RequestMapping("")
    public String index(Model model) {
        //model.addAttribute("dicMap",sdsStandDicService.getDicMapBySource("抗菌药物"));
        return PREFIX + "cdssstandardmatch.html";
    }

    /**
     * 获取cdss推荐信息的tree列表
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> cdssRecommendTree() {
        return cdssStandardMatchService.buildCdssRecommendTree();
    }


    /**
     * 修改关键字
     */
    @RequestMapping(value = "/updateKeyword")
    @ResponseBody
    public Object updateKeyword(CdssRecommendKeywordEntity cdssRecommendKeywordEntity) {
        if (CommonUtil.isOneEmpty(cdssRecommendKeywordEntity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            // 这三个因为前台需要输入特殊字符，前台已转码，因此后台也需要转码
            cdssRecommendKeywordEntity.setKeyword(java.net.URLDecoder.decode(cdssRecommendKeywordEntity.getKeyword(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String itemId = cdssRecommendKeywordService.getItemIdByType(cdssRecommendKeywordEntity.getCdssRecommendId(), cdssRecommendKeywordEntity.getRecommendType());

        CdssRecommendKeywordEntity old = cdssRecommendKeywordService.selectOne(new EntityWrapper<CdssRecommendKeywordEntity>()
        .eq("recommend_type", cdssRecommendKeywordEntity.getRecommendType())
        .eq("item_id", itemId)
        .eq("qcentity_id", cdssRecommendKeywordEntity.getQcentityId()));
        if (CommonUtil.isEmpty(old)) {
            cdssRecommendKeywordEntity.setItemId(itemId);
            cdssRecommendKeywordEntity.insert();
        } else {
            old.setKeyword(cdssRecommendKeywordEntity.getKeyword());
            old.updateAllColumnById();
        }
        return R.ok();
    }


    /**
     *
     */
    @RequestMapping(value = "/getKeyword")
    @ResponseBody
    public Object getKeyword(@RequestParam Long cdssRecommendId, @RequestParam String matchType, @RequestParam Long entityId) {

        String itemId = cdssRecommendKeywordService.getItemIdByType(cdssRecommendId, matchType);

        CdssRecommendKeywordEntity cdssRecommendKeywordEntity = cdssRecommendKeywordService.selectOne(new EntityWrapper<CdssRecommendKeywordEntity>()
                .eq("recommend_type", matchType)
                .eq("item_id", itemId)
                .eq("qcentity_id", entityId));
        if (StringUtils.isEmpty(cdssRecommendKeywordEntity)){
            return "";
        }else {
            return cdssRecommendKeywordEntity.getKeyword();
        }
    }

    /**
     * @Description: 查询禁忌症对照数据
     * @Title: selectContraindicationMatch
     * @return: Object
     * @author: YangHangwei
     * @date:2024-01-28 16:15:15
     */
    @RequestMapping("selectContraindicationMatch")
    @ResponseBody
    public Object selectContraindicationMatch(@RequestParam Map<String, Object> params) {
        return R.packForBT(sdcCdssContraindicationMatchService.pageMatchContraindication(params));
    }

    /**
     * @Description: 查询医嘱对照数据
     * @Title: selectOrderMatch
     * @return: Object
     * @author: zhangdc
     * @date:2022-03-23 10:09:15
     */
    @RequestMapping("selectOrderMatch")
    @ResponseBody
    public Object selectOrderMatch(@RequestParam Map<String, Object> params) {

        String currentPage = (String) params.get("page");
        String size = (String) params.get("rows");
        String compare = (String) params.get("compare");
        String matchType = (String) params.get("matchType");

        if (Objects.equals("match", compare)){
            Page<SdcCdssItemMatchEntity> page = new Page<SdcCdssItemMatchEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<CdcOrdmastDto> result = sdcCdssItemMatchService.pageMatchOrder(page,params);

            Page<CdcOrdmastDto> dtoPage = new Page<CdcOrdmastDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }else {
            Page<CdcOrdmastEntity> page = new Page<CdcOrdmastEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<CdcOrdmastDto> result = sdcCdssItemMatchService.pageOrder(page,params);

            Page<CdcOrdmastDto> dtoPage = new Page<CdcOrdmastDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }
    }

    /**
     * @Description: 查询检验对照数据
     * @Title: selectOrderMatch
     * @return: Object
     * @author: zhangdc
     * @date:2022-03-23 10:09:15
     */
    @RequestMapping("selectLisMatch")
    @ResponseBody
    public Object selectLisMatch(@RequestParam Map<String, Object> params) {
        //过滤医嘱为检验的
        CdcDictionaryEntity dictionaryEntity = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "Lab");
        if (!StringUtils.isEmpty(dictionaryEntity)){
            params.put("busOrderCateId",dictionaryEntity.getId());
        }

        String currentPage = (String) params.get("page");
        String size = (String) params.get("rows");
        String compare = (String) params.get("compare");

        if (Objects.equals("match", compare)){
            Page<SdcCdssItemMatchEntity> page = new Page<SdcCdssItemMatchEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<CdcOrdmastDto> result = sdcCdssItemMatchService.pageMatchOrder(page,params);

            Page<CdcOrdmastDto> dtoPage = new Page<CdcOrdmastDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }else {
            Page<CdcOrdmastEntity> page = new Page<CdcOrdmastEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<CdcOrdmastDto> result = sdcCdssItemMatchService.pageOrder(page,params);

            Page<CdcOrdmastDto> dtoPage = new Page<CdcOrdmastDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }
    }



    /**
     * @Description: 查询检查对照数据
     * @Title: selectOrderMatch
     * @return: Object
     * @author: zhangdc
     * @date:2022-03-23 10:09:15
     */
    @RequestMapping("selectRisMatch")
    @ResponseBody
    public Object selectRisMatch(@RequestParam Map<String, Object> params) {
        //过滤医嘱为检查的
        CdcDictionaryEntity dictionaryEntity = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "Check");
        if (!StringUtils.isEmpty(dictionaryEntity)){
            params.put("busOrderCateId",dictionaryEntity.getId());
        }
        String currentPage = (String) params.get("page");
        String size = (String) params.get("rows");
        String compare = (String) params.get("compare");

        if (Objects.equals("match", compare)){
            Page<SdcCdssItemMatchEntity> page = new Page<SdcCdssItemMatchEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<CdcOrdmastDto> result = sdcCdssItemMatchService.pageMatchOrder(page,params);

            Page<CdcOrdmastDto> dtoPage = new Page<CdcOrdmastDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }else {
            Page<CdcOrdmastEntity> page = new Page<CdcOrdmastEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<CdcOrdmastDto> result = sdcCdssItemMatchService.pageOrder(page,params);

            Page<CdcOrdmastDto> dtoPage = new Page<CdcOrdmastDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }
    }

    /**
     * @Description: 查询评估量表对照数据
     * @Title: selectEvalMatch
     * @return: Object
     * @author: zhangdc
     * @date:2022-03-23 10:09:15
     */
    @RequestMapping("selectEvalMatch")
    @ResponseBody
    public Object selectEvalMatch(@RequestParam Map<String, Object> params) {
        String currentPage = (String) params.get("page");
        String size = (String) params.get("rows");
        String compare = (String) params.get("compare");

        if (Objects.equals("match", compare)){
            Page<SdcCdssItemMatchEntity> page = new Page<SdcCdssItemMatchEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<SdcBaseAssessmentDto> result = sdcCdssItemMatchService.pageMatchAssessment(page,params);

            Page<SdcBaseAssessmentDto> dtoPage = new Page<SdcBaseAssessmentDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }else {
            Page<SdcBaseAssessmentEntity> page = new Page<SdcBaseAssessmentEntity>(Integer.parseInt(currentPage), Integer.parseInt(size));
            List<SdcBaseAssessmentDto> result = sdcCdssItemMatchService.pageAssessment(page,params);

            Page<SdcBaseAssessmentDto> dtoPage = new Page<SdcBaseAssessmentDto>(Integer.parseInt(currentPage), Integer.parseInt(size));
            BeanUtil.copyProperties(page,dtoPage);
            dtoPage.setRecords(result);
            return R.packForBT(dtoPage);
        }
    }


    /**
     * 跳转到导入CAP方案对照关键字的页面
     */
    @RequestMapping("/to_import")
    public String toImport() {
        return PREFIX + "import.html";
    }

    /**
     * 导入CAP方案对照关键字
     */
    @RequestMapping(method = RequestMethod.POST, path = "/import")
    @ResponseBody
    public R importItem(@RequestPart("file") MultipartFile file) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream(),0);
            List<List<Object>> itemAll = reader.read();
            cdssRecommendKeywordService.importKeyword(itemAll);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 根据关键字自动匹配
     */
    @RequestMapping(value = "/autoCompare")
    @ResponseBody
    public Object autoCompare(@RequestParam Long cdssRecommendId, @RequestParam String cdssRecommendName, @RequestParam String recommendType) {
        this.cdssStandardMatchService.autoCompare(cdssRecommendId, cdssRecommendName, recommendType);
        return R.ok();
    }

    @RequestMapping(value = "/compare")
    @ResponseBody
    public Object compare(@RequestParam Long cdssRecommendId, @RequestParam String orderIDStr, @RequestParam String matchType) {

        this.cdssStandardMatchService.compare(cdssRecommendId, orderIDStr, matchType);

        return R.ok();
    }

    /**
     * 勾选添加cdss和禁忌症关联
     * @author yanghangwei
     * @param params
     * @return
     */
    @RequestMapping(value = "/comparecon")
    @ResponseBody
    public Object compareCon(@RequestParam Map<String, Object> params) {
        sdcCdssContraindicationMatchService.compare(params);
        return R.ok();
    }

    @RequestMapping(value = "/undo")
    @ResponseBody
    public Object undo(@RequestParam Long cdssRecommendId, @RequestParam String orderIDStr, @RequestParam String matchType) {
        this.cdssStandardMatchService.undo(cdssRecommendId, orderIDStr, matchType);

        return R.ok();
    }

    /**
     * 取消勾选移除cdss和禁忌症关联
     * @author yanghangwei
     * @param params
     * @return
     */
    @RequestMapping(value = "/undocon")
    @ResponseBody
    public Object undo(@RequestParam Map<String, Object> params) {
        sdcCdssContraindicationMatchService.undo(params);
        return R.ok();
    }

    @RequestMapping(value = "/updateIsDefault")
    @ResponseBody
    public Object updateIsDefault(@RequestParam Long cdssRecommendId, @RequestParam Long orderID, @RequestParam String matchType, @RequestParam Integer isDefault) {

        this.cdssStandardMatchService.updateIsDefault(cdssRecommendId, orderID, matchType, isDefault);

        return R.ok();
    }

}
